package lambdasinaction.chap5;

import lambdasinaction.chap4.Dish;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static lambdasinaction.chap4.Dish.menu;

/**
 * Created by ThinkPad on 2017/8/18.
 */
public class Maping {
    public static void main(String... args) {
//        map
        List<String> dishNames = menu.stream()
                .map(Dish::getName)
                .collect(Collectors.toList());
        System.out.println(dishNames);

//        map
        List<String> words = Arrays.asList("Hello","World");
        List<Integer> wordLengths = words.stream()
                .map(String::length)
                .collect(Collectors.toList());
        System.out.println(wordLengths);

//        flatMap
        words.stream()
                .flatMap((String line) -> Arrays.stream(line.split("")))
                .distinct()
                .forEach(System.out::println);

//        flatMap
//        给定(1,2,3)(3,4)两个数列,返回所有数对
//        (1,3)(1,4)(2,3)(2,4)(3,3)(3,4)
        List<Integer> number1 = Arrays.asList(1,2,3);
        List<Integer> number2 = Arrays.asList(3,4);
        List<int[]> pairs1 =
                number1.stream()
                .flatMap(integer -> number2.stream().map(integer1 -> new int[]{integer,integer1}))
                .collect(Collectors.toList());
        pairs1.forEach(ints -> System.out.println("(" + ints[0] + "," + ints[1] + ")"));

//        flatMap
//        给定两个数列
//        返回能被3整数的所有数对
        List<Integer> number3 = Arrays.asList(1,2,3,4,5);
        List<Integer> number4 = Arrays.asList(6,7,8);
        List<int[]> pairs2 =
                number3.stream()
                .flatMap((Integer i) -> number4.stream()
                        .map((Integer j) -> new int[]{i,j})
                )
                .filter(pair -> (pair[0] + pair[1]) % 3 == 0)
                .collect(Collectors.toList());
        pairs2.forEach(pair -> System.out.println("(" + pair[0] + "," + pair[1] + ")"));
    }
}
